package com.homevip.web.interceptor;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.homevip.core.util.ResponseUtil;
import com.homevip.user.entity.User;
import com.homevip.user.entity.User_role;
import com.homevip.user.service.UserService;
import com.homevip.util.UserSessionUtil;
import com.homevip.util.system.Const;
import com.homevip.util.system.PlatformMenuUtil;
import com.homevip.web.annotation.*;
import com.homevip.web.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Set;
 
/**
 *	管理平台拦截
 */
public class PlatformInterceptor extends HandlerInterceptorAdapter{
	private Set<String> m_excludes;
	private static final String PATH_PF = "/platform";
	
	private String[] m_suffixs = Const.RESOURCES;

	private String[] m_edit = Const.FLAG_EDIT;
	
	@Autowired 
	UserService userrService;
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String currentPath = PATH_PF;
		boolean isLogin = false;
		String contextPath;
		String requestURI;
		String query;
		HandlerMethod handlerMethod = null;
		DataTypeAnnotation dataType = null;
		ActionTypeAnnotation actionType = null;
		ExcludeAuthAnnotation exclude = null;
		User user;
	
		contextPath = request.getContextPath();
		requestURI = request.getRequestURI().replaceAll("\\/\\/", "/");

		//过滤后缀,直接跳过
		for (String suffix : m_suffixs) {
			if (requestURI.endsWith("." + suffix)) {
				return super.preHandle(request, response, handler);
			}
		}

		//被标记为例外的方法不需要鉴权
		if(null != handler){
			handlerMethod = (HandlerMethod)handler;
			exclude = handlerMethod.getMethodAnnotation(ExcludeAuthAnnotation.class);
		}
		if(null != exclude && exclude.value()){
			return super.preHandle(request, response, handler);
		}
		//例外列表
		for (String ex : m_excludes) {
			if (requestURI.equals(contextPath + ex)) {
				return super.preHandle(request, response, handler);
			}
		}
		
		user = UserSessionUtil.getUser(request);
		if(null != user && 0 != user.getId()){
			isLogin = true;
		}

		if(null != handler){
			handlerMethod = (HandlerMethod)handler;
			dataType = handlerMethod.getMethodAnnotation(DataTypeAnnotation.class);
			actionType = handlerMethod.getMethodAnnotation(ActionTypeAnnotation.class);
		}
		if(!isLogin){
			redirectTo(dataType, contextPath + currentPath, requestURI, "请登录。", request, response);
			return false;
		}
		
		//初始管理员不鉴权
		if(Const.ADMINUSER_NAME.equals(user.getAccount())){
			return true;
		}
		
		if(PlatformMenuUtil.isDefaultUrl(requestURI)){
			return true;
		}
		
		JsonObject menu = PlatformMenuUtil.getMenu(user, request);
		JsonArray ja = menu.get("item").getAsJsonArray();
		for (JsonElement je : ja) {
			JsonObject cmenu1 = je.getAsJsonObject();
			JsonArray menus2 = cmenu1.get("item").getAsJsonArray();
			for (JsonElement cje2 : menus2) {
				JsonObject cmenu2 = cje2.getAsJsonObject();
				JsonArray menus3 = cmenu2.get("item").getAsJsonArray();
				for (JsonElement cje3 : menus3) {
					JsonObject cmenu3 = cje3.getAsJsonObject();
					String url = cmenu3.get("url").getAsString();
					//先匹配，看看是否模块首页
					if(requestURI.indexOf(url) > -1){
						return true;
					}else{
						//若不匹配，截取最后的“/”，尝试匹配其子页面
						url = url.substring(0, url.lastIndexOf("/") + 1);
						if(requestURI.indexOf(url) > -1){
							return true;
						}
					}
				}
			}
		}
		redirectTo(dataType, contextPath + currentPath, requestURI, "不能访问。", request, response);
		return false;
	}
	
	public void setExcludes(Set<String> excludes) {
		m_excludes = excludes;
	}
	
	void sendRedirectScript(String gotoUrl, HttpServletResponse response) throws IOException{
		String str = "<script>location.href=\"" + gotoUrl + "\";</script>";
		response.getWriter().print(str);
		response.getWriter().flush();
		response.getWriter().close();
	}
	
	//调到对应登陆地址
	void redirectTo(DataTypeAnnotation dt, String path, String requestURI, String msg, HttpServletRequest request, HttpServletResponse response) throws Exception{
		String url;
		String query;
		query = request.getQueryString();
		if (null != query && query.length() > 0) {
			requestURI += "%3f" + URLEncoder.encode(query, Const.UTF8);
		}
		
		url = path  + "/login?ref="+URLEncoder.encode(requestURI,Const.UTF8);
		
		//默认跳转
		if(null == dt){
			sendRedirectScript(url, response);
		}else{
			// 根据注解设置的值 得知是返回页面是否json
			if(DataTypeEnum.json == dt.value()){
				// 返回json格式数据提示
				ResultVo resultVo = new ResultVo(false, msg); 
				ResponseUtil.outJson(resultVo.toJsonMsg(), response);
			}else{
				sendRedirectScript(url, response);
			}
		}
	}
	
}
